package com.zzyl.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
public class AliyunOSSOperator {
    @Autowired
    private AliyunOSSProperties ossProperties;
    
    public String upload(byte[] content,String originalFilename) throws Exception {
        String endpoint=ossProperties.getEndpoint();
        String bucketName=ossProperties.getBucketName();
        String accessKeyId=ossProperties.getAccessKeyId();
        String accessKeySecret=ossProperties.getAccessKeySecret();
        
        // 填写Object完整路径，例如202406/1.png。Object完整路径中不能包含Bucket名称。
        // 获取当前系统日期的字符串,格式为 yyyy/MM
        String dir=LocalDate.now()
                            .format(DateTimeFormatter.ofPattern("yyyy/MM"));
        // 根据原始文件名originalFilename, 生成一个新的不重复的文件名
        String newFileName=UUID.randomUUID()
                               .toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName=dir + "/" + newFileName;
        
        // 创建OSSClient实例。
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        
        // 文件上传
        try {
            ossClient.putObject(bucketName,objectName,new ByteArrayInputStream(content));
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        
        return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
    }
}
